package com.magictower.primary.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.magictower.primary.R;
import com.magictower.primary.common.SPConstant;
import com.magictower.primary.db.dao.AddressDao;

/**
 * @author kejunzhan
 * @since 2017/12/19
 */

public class ShowLocationService extends Service {
    protected static final String TAG = "ShowLocationService";
    private SharedPreferences mPref;
    long[] mHits = new long[2];// 数组长度表示要点击的次数
    private WindowManager.LayoutParams mParams;
    private WindowManager windowManager;
    private View view;
    private int statusBarHeight;
    private OutCallReceiver receiver;
    private MyPhoneListener listener;
    private TelephonyManager tm;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mPref = getSharedPreferences(SPConstant.CONFIG, MODE_PRIVATE);
        // 得到窗体管理器
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        //注册广播
        receiver = new OutCallReceiver();
        registerReceiver(receiver, new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL));
        //电话监听器
        listener = new MyPhoneListener();
        tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (receiver !=null) {
            unregisterReceiver(receiver);
            receiver = null;
        }
        if (listener != null ){
            tm.listen(listener, PhoneStateListener.LISTEN_NONE);
            listener = null;
        }
    }

    /**
     * 自定义的土司，把归属地显示在界面上。
     */
    public void showMyToast(String number) {
        view = View.inflate(ShowLocationService.this, R.layout.toast_show, null);
        TextView tv_address = (TextView) view.findViewById(R.id.tv_address);
        tv_address.setText(number);
        //手机状态框高度
        statusBarHeight = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height")
                    .get(object).toString());
            statusBarHeight = getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        final int winWidth = windowManager.getDefaultDisplay().getWidth();
        final int winHeight = windowManager.getDefaultDisplay().getHeight() - statusBarHeight;

        //获取拖动框的背景
        int style = mPref.getInt(SPConstant.TOAST_STYLE, 0);
        view.setBackgroundResource(SPConstant.ITEMS_ID[style]);
        mParams = new WindowManager.LayoutParams();
        mParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        mParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        //修改完左上角对其
        mParams.gravity = Gravity.START+Gravity.TOP;
        mParams.x = mPref.getInt(SPConstant.TOAST_X, 0);
        mParams.y = mPref.getInt(SPConstant.TOAST_Y, 0);
        mParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
        mParams.format = PixelFormat.TRANSLUCENT;
        mParams.type = WindowManager.LayoutParams.TYPE_PRIORITY_PHONE;
        // 把view添加到手机窗体上。
        windowManager.addView(view, mParams);
        System.out.println("把view添加到手机窗体上。");

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
                mHits[mHits.length - 1] = SystemClock.uptimeMillis();// 开机后开始计算的时间
                if (mHits[0] >= (SystemClock.uptimeMillis() - 500)) {
                    // 居中
                    mParams.x = (winWidth-view.getWidth()) / 2;
                    mParams.y = (winHeight-view.getHeight()) / 2;
                    windowManager.updateViewLayout(view, mParams);
                }
            }
        });

        view.setOnTouchListener(new View.OnTouchListener() {
            int startX;
            int startY;
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        startX = (int) event.getRawX();
                        startY = (int) event.getRawY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        int endX = (int) event.getRawX();
                        int endY = (int) event.getRawY();

                        // 计算移动偏移量
                        int dx = endX - startX;
                        int dy = endY - startY;

                        // 更新左上右下距离
                        int l = view.getLeft() + dx;
                        int r = view.getRight() + dx;
                        int t = view.getTop() + dy;
                        int b = view.getBottom() + dy;

                        // 判断是否超出屏幕边界, 注意状态栏的高度
                        if (l < 0 || r > winWidth || t < 0 || b > winHeight) {
                            break;
                        }
                        view.layout(l, t, r, b);//重新定义位置
                        //重新初始化坐标
                        startX = (int) event.getRawX();
                        startY = (int) event.getRawY();
                        break;
                    case MotionEvent.ACTION_UP:
                        //保存数据
                        SharedPreferences.Editor editor = mPref.edit();
                        editor.putInt(SPConstant.TOAST_X, view.getLeft());
                        editor.putInt(SPConstant.TOAST_Y, view.getTop());
                        editor.apply();
                        break;
                }
                return false;
            }
        });
    }

    private class MyPhoneListener extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);
            switch (state) {
                case TelephonyManager.CALL_STATE_IDLE:
                    //空闲
                    if (view !=null) {
                        windowManager.removeView(view);
                        view = null;
                    }
                    break;
                case TelephonyManager.CALL_STATE_RINGING:
                    //响铃
                    String address = AddressDao.getAddress(incomingNumber);
                    showMyToast(address);
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    //接通
                    break;
            }
        }
    }

    /**
     * 外拨电话的广播接受者
     */
    private class OutCallReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String number = getResultData();
            String address = AddressDao.getAddress(number);
            showMyToast(address);
        }
    }
}
